package com.common.help.test12;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class NIOClient {
	SocketChannel client;
	InetSocketAddress address = new InetSocketAddress("localhost",8080);
	Selector selector;
	ByteBuffer revice = ByteBuffer.allocate(1024);
	ByteBuffer send = ByteBuffer.allocate(1024);
	public NIOClient() throws IOException{
		client = SocketChannel.open();
		client.configureBlocking(false);
		client.connect(address);
		
		selector = Selector.open();
		client.register(selector, SelectionKey.OP_CONNECT);
	}
	
	public void session() throws IOException{
		if(client.isConnectionPending()){
			client.finishConnect();
			System.out.println("请客户端输入登记");
			client.register(selector, SelectionKey.OP_WRITE);
		}
		Scanner s = new Scanner(System.in);
		while(s.hasNext()){
			String name = s.next();
			if("".equals(name)){
				continue;
			}
			proocess(name);
		}
	}

	private void proocess(String name) throws IOException {
		boolean unfinish = true;
			while(unfinish){
				int i = selector.select();//判断当前有没有 客户排队
				if(i == 0){continue;}
				
				Set<SelectionKey> keys = selector.selectedKeys();
				Iterator<SelectionKey> iterator = keys.iterator();
				while(iterator.hasNext()){
					SelectionKey key = iterator.next();
					if(key.isWritable()){
						send.clear();
						send.put(name.getBytes());
						send.flip();
						client.write(send);
						client.register(selector, SelectionKey.OP_READ);
					}else if(key.isReadable()){
						revice.clear();
						int len = client.read(revice);
						if(len>0){
							revice.flip();
							System.out.println("获取到服务端反馈的信息"+new String(revice.array(),0,len));
						}
						client.register(selector, SelectionKey.OP_WRITE);
						unfinish = false;
					}
				}
			}
	}
	public static void main(String[] args) throws IOException {
		new NIOClient().session();
	}
}
